#include "stdafx.h"

extern WSASetLastError_proxy_t pTrueWSASetLastError;

int select_proxy (
    __in    int     nfds,
    __inout fd_set* readfds,
    __inout fd_set* writefds,
    __inout fd_set* exceptfds,
    __in    const struct timeval* timeout
    )
{
    try
    {
    //SEND
        Header header(GetCurrentThreadId(), "select");
        select_in_inout selectIN(nfds, readfds, writefds, exceptfds, timeout);
        
        std::vector<char> out_buffer;
        Serialize(header, selectIN, out_buffer);

        SendToClient (out_buffer);
        
    //RECEIVE()
        select_out_inout selectOUT;

        std::vector<char> in_buffer;
        
        RecvFromClient (in_buffer, header);
        Deserialize deserialize(in_buffer);
        deserialize(selectOUT);

        if(selectOUT.wsa_last_error_ != 0)
        {
            pTrueWSASetLastError(selectOUT.wsa_last_error_);
            return SOCKET_ERROR;
        }
        
        memcpy (readfds, selectOUT.readfds_, sizeof(fd_set));
        memcpy (writefds, selectOUT.writefds_, sizeof(fd_set));
        memcpy (exceptfds, selectOUT.exceptfds_, sizeof(fd_set));
        return selectOUT.ret_;
    }
    catch (std::exception& ex)
    {
        LOG(plog::error) << "select: " << ex.what();
    }
    pTrueWSASetLastError (WSAEWOULDBLOCK);
    return SOCKET_ERROR;
}
